package com.durian.base.update.ui

import android.app.ProgressDialog
import com.durian.base.frame.activity.ActivityFrame
import com.durian.base.frame.fragment.FragmentFrame
import com.durian.base.update.entity.DownloadEntity
import com.durian.base.update.entity.VersionEntity
import com.durian.base.update.entity.XUpdateCheckErrorCode
import com.durian.base.update.entity.XUpdateException
import com.durian.base.update.proxy.IUpdateInstallController
import com.durian.base.update.proxy.IUpdateVersionController
import com.durian.base.update.proxy.impl.DefaultUpdateListener
import com.durian.base.utils.ToastUtils
import com.durian.ui.dialog.DialogAlert

/**
 * 说明：有弹窗监听
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2021/1/22 22:48
 * <p/>
 * 版本：version 1.0
 */
class LeadUpdateListener private constructor(val activity: ActivityFrame, val leadConfig: Config) : DefaultUpdateListener() {

    private var progressDialog: ProgressDialog? = null

    class Config(
            /**
             * 显示检查Loading
             */
            var showCheckLoading: Boolean = true,
            /**
             * 显示下载进度条
             */
            var showDownloadLoading: Boolean = true,
            /**
             * 显示更新弹窗
             */
            var showNewVersionDialog: Boolean = true,
            /**
             * 显示安装弹窗
             */
            var showInstallDialog: Boolean = false,
            /**
             * 没有网络提示
             */
            var noNetworkTip: String = "网络连接失败",
            /**
             * 未知错误提示
             */
            var unKnownErrorTip: String = "请求失败",
            /**
             * 没有新版本提示
             */
            var noNewVersionTip: String = "当前已经是最新版本了",
            /**
             * 默认更新日志
             */
            var defaultUpdateLog: String = "",
            /**
             * 更新提示框标题
             */
            var newVersionDialogTitle: String = "更新提示",
            /**
             * 更新提示框取消
             */
            var newVersionDialogCancelText: String = "取消",
            /**
             * 更新提示框确定
             */
            var newVersionDialogConfirmText: String = "去更新",
            /**
             * 更新提示框标题
             */
            var newVersionInstallDialogTitle: String = "更新提示",
            /**
             * 更新提示框取消
             */
            var newVersionInstallDialogCancelText: String = "取消",
            /**
             * 更新提示框确定
             */
            var newVersionInstallDialogConfirmText: String = "去安装",
            /**
             * 下载框标题
             */
            var downloadDialogTitle: String = "正在下载中...",
            /**
             * 下载框确定
             */
            var downloadDialogConfirmText: String = "关闭",
            /**
             * 下载异常提示
             */
            var downloadErrorTip: String = "下载错误"
    )

    companion object {
        fun Config(fragment: FragmentFrame, apply: (Config) -> Unit): LeadUpdateListener {
            val config = Config().apply(apply)
            return LeadUpdateListener(fragment.activity(), config)
        }
        fun Config(activity: ActivityFrame, apply: (Config) -> Unit): LeadUpdateListener {
            val config = Config().apply(apply)
            return LeadUpdateListener(activity, config)
        }
    }

    override fun doCheckUpdateBefore() {
        if (leadConfig.showCheckLoading) {
            activity.showLoading(false)
        }
    }

    override fun doCheckUpdateAfter() {
        if (leadConfig.showCheckLoading) {
            activity.dismissLoading()
        }
    }

    override fun doCheckUpdateException(exception: XUpdateException) {
        if (leadConfig.showCheckLoading) {
            activity.dismissLoading()
        }
        when (exception.errorCode) {
            XUpdateCheckErrorCode.NoNetwork -> {
                ToastUtils.get().shortToast(leadConfig.noNetworkTip)
            }
            XUpdateCheckErrorCode.Unknown -> {
                ToastUtils.get().shortToast(leadConfig.unKnownErrorTip)
            }
        }
    }

    override fun isDownloading() {
        if (leadConfig.showDownloadLoading) {
            progressDialog?.let {
                if (!it.isShowing){
                    it.show()
                }
            }
        }
    }

    override fun noNewVersion() {
        ToastUtils.get().shortToast(leadConfig.noNewVersionTip)
    }

    override fun findNewVersion(updateController: IUpdateVersionController, versionEntity: VersionEntity) {
        if (versionEntity.forceUpdate){
            leadConfig.showInstallDialog = true
            leadConfig.downloadDialogConfirmText = ""
        }

        if (leadConfig.showNewVersionDialog) {
            val log = if (versionEntity.updateLog.isEmpty()) {
                if (leadConfig.defaultUpdateLog.isNotEmpty()) {
                    leadConfig.defaultUpdateLog
                } else {
                    "发现新版本(v${versionEntity.versionName})~"
                }
            } else {
                versionEntity.updateLog
            }
            val dialog = DialogAlert.create(activity)
                    .setTitle(leadConfig.newVersionDialogTitle)
                    .setMessage(log)
                    .setCancel(false)
            if (versionEntity.forceUpdate) {
                dialog.setConfirmText(leadConfig.newVersionDialogConfirmText)
                        .setConfirmListener { dialog, _ ->
                            dialog.dismiss()
                            updateController.download(versionEntity)
                        }
            } else {
                dialog.setConfirmText(leadConfig.newVersionDialogConfirmText)
                        .setConfirmListener { dialog, _ ->
                            dialog.dismiss()
                            updateController.download(versionEntity)
                        }
                        .setCancelText(leadConfig.newVersionDialogCancelText)
                        .setCancelListener { dialog, _ ->
                            dialog.dismiss()
                            updateController.cancelUpdate()
                        }
            }
            dialog.show()
        } else {
            updateController.download(versionEntity)
        }
    }

    override fun installNewVersion(updateController: IUpdateInstallController, downloadEntity: DownloadEntity) {
        if (leadConfig.showInstallDialog) {
            val log = if (downloadEntity.versionEntity.updateLog.isEmpty()) {
                if (leadConfig.defaultUpdateLog.isNotEmpty()) {
                    leadConfig.defaultUpdateLog
                } else {
                    "发现新版本(v${downloadEntity.versionEntity.versionName})~"
                }
            } else {
                downloadEntity.versionEntity.updateLog
            }
            val dialog = DialogAlert.create(activity)
                    .setTitle(leadConfig.newVersionInstallDialogTitle)
                    .setMessage(log)
                    .setCancel(false)
            if (downloadEntity.versionEntity.forceUpdate) {
                dialog.setConfirmText(leadConfig.newVersionInstallDialogConfirmText)
                        .setConfirmListener { _, _ ->
                            updateController.install(downloadEntity)
                        }
            } else {
                dialog.setConfirmText(leadConfig.newVersionInstallDialogConfirmText)
                        .setConfirmListener { dialog, _ ->
                            dialog.dismiss()
                            updateController.install(downloadEntity)
                        }
                        .setCancelText(leadConfig.newVersionInstallDialogCancelText)
                        .setCancelListener { dialog, _ ->
                            dialog.dismiss()
                            updateController.cancelInstall()
                        }
            }
            dialog.show()
        } else {
            updateController.install(downloadEntity)
        }
    }

    override fun doDownloadApkBefore() {
        if (leadConfig.showDownloadLoading) {
            progressDialog = ProgressDialog(activity).apply {
                setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                setCancelable(false)
                setTitle(leadConfig.downloadDialogTitle)
                if (leadConfig.downloadDialogConfirmText.isNotEmpty()){
                    setButton(leadConfig.downloadDialogConfirmText) { dialog, _ ->
                        dialog?.dismiss()
                        progressDialog = null
                    }
                }
                progress = 0
                max = 100
            }
            progressDialog?.show()
        }
    }

    override fun doDownloadApkAfter() {
        if (leadConfig.showDownloadLoading) {
            progressDialog?.dismiss()
        }
    }

    override fun doDownloadApkException(exception: XUpdateException) {
        ToastUtils.get().shortToast(leadConfig.downloadErrorTip)
        if (leadConfig.showDownloadLoading){
            progressDialog?.dismiss()
        }
    }

    override fun doDownloadApkProgress(progress: Int, current: Long, total: Long) {
        if (leadConfig.showDownloadLoading) {
            progressDialog?.let {
                it.max = total.toInt()
                it.progress = current.toInt()
            }
        }
    }

}